import L from 'leaflet';
import 'leaflet.heat';
import { isLngLat } from 'src/util/mapUtil';
import { withLeaflet, GridLayer } from 'react-leaflet';
import setting from './setting';

class HeatMapLayer extends GridLayer {
  handleProps({ data, config }) {
    let heatData = [];
    if (Array.isArray(data) && data.length > 0) {
      heatData = data.filter(({ lat = '', lng = '' }) => isLngLat(lng, lat))
        .map(({ lat, lng, intensity = 1 }) => (
          [lat, lng, intensity]
        ));
    }
    return {
      heatData,
      config
    };
  }

  getGradient(colors) {
    if (!Array.isArray(colors)) return {};

    return colors.reduce(
      (obj, item) => (Object.assign(obj, { [item.end / 100]: item.color })),
      {}
    );
  }

  get propsStringify() {
    const { config, data } = this.props;
    return JSON.stringify({ config, data });
  }

  createLeafletElement(props) {
    const { heatData, config } = this.handleProps(props);
    this.prevString = this.propsStringify;
    const gradient = this.getGradient(config.colors);
    return L.heatLayer(heatData, { ...config, gradient });
  }

  /**
  * @param {from} 上一次数据
  * @param {to} 新的数据
  */
  updateLeafletElement(from, to) {
    if (this.prevString === this.propsStringify) return;
    this.prevString = this.propsStringify;
    const { heatData, config } = this.handleProps(to);
    const gradient = this.getGradient(config.colors);

    try {
      this.leafletElement.setOptions({
        ...config,
        gradient
      });
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    }
    this.leafletElement.setLatLngs(heatData);
  }
}

HeatMapLayer.setting = setting;


export default withLeaflet(HeatMapLayer);
